package com.cskaoyan.config;

import com.cskaoyan.converter.StringToUserConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * @author stone
 * @date 2022/08/09 09:50
 */
@ComponentScan("com.cskaoyan.controller")
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer/*, ApplicationContextAware*/ {

    //@Autowired
    //StringToUserConverter stringToUserConverter;

    /*@Override
    public void addFormatters(FormatterRegistry registry) {
        //registry.addConverter(new StringToUserConverter());
        registry.addConverter(stringToUserConverter);
    }*/

    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // Converter bean = applicationContext.getBean(Converter.class);
        // key是组件id，value是组件实例
        Map<String, Converter> beansOfType = applicationContext.getBeansOfType(Converter.class);
        // 取出map中的所有value → 所有的实例
        Collection<Converter> beans = beansOfType.values();
        Iterator<Converter> iterator = beans.iterator();
        while (iterator.hasNext()) {
            Converter converter = iterator.next();
            registry.addConverter(converter);
        }
    }
}
